package com.feng.cloud.system.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feng.cloud.common.constants.SystemConstant;
import com.feng.cloud.common.request.QueryRequest;
import com.feng.cloud.common.response.TableResultResponse;
import com.feng.cloud.common.utils.SortUtils;
import com.feng.cloud.system.entity.Column;
import com.feng.cloud.system.entity.GeneratorConfig;
import com.feng.cloud.system.entity.Table;
import com.feng.cloud.system.mapper.GeneratorMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName GeneratorService
 * @Description TODO
 * @Author Better Feng
 * @Date 2019/12/23 13:53
 * @Version 1.0
 **/
@Service
@AllArgsConstructor
public class GeneratorService {

    private GeneratorMapper generatorMapper;

    /**
     * 查询所有数据库
     * @return List<String>
     */
    public List<String> getDatabases() {
        return generatorMapper.getDatabases();
    }

    /**
     *
     * @param tableName 表名
     * @param request QueryRequest
     * @param databaseType databaseType
     * @param schemaName schemaName
     * @return IPage<Table>
     */
    public IPage<Table> getTables(String tableName, QueryRequest request, String databaseType, String schemaName) {
        Page<Table> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtils.handlePageSort(request, page, "createTime", SystemConstant.ORDER_ASC, false);
        return generatorMapper.getTables(page, tableName, schemaName);
    }

    /**
     * 列表查询
     * @param request QueryRequest
     * @return
     */
    public TableResultResponse<Table> selectList(QueryRequest request) {
        Page<Table> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtils.handlePageSort(request, page, "createTime", SystemConstant.ORDER_ASC, false);
        String tableName = request.getValue(GeneratorConfig::getTableName, String.class);
        String tableSchema = request.getValue(GeneratorConfig::getTableSchema, String.class);
        IPage<Table> iPage = generatorMapper.getTables(page, tableName, tableSchema);
        return new TableResultResponse<>(iPage.getTotal(), iPage.getRecords());
    }

    public List<Column> getColumns(String schemaName, String tableName) {
        return generatorMapper.getColumns(schemaName, tableName);
    }
}
